import {
  Body,
  Controller,
  Delete,
  Get,
  Header,
  Post,
  Put,
  Query,
  Req,
  Res,
  StreamableFile,
  UseInterceptors,
} from '@nestjs/common';
import { AuthInterceptor } from '../../config/filter/auth.interceptor';

import { ForecostService } from './forecost.service';
import { Result } from '../../common/result/Result';
import { BomVo } from './dto/bom.vo';
import { RunLaborHoursCreate } from '../../common/api/StdWorkingHours';
import { DictService } from '../06_dict/dict.service';

@Controller('/api/v1/forecast')
export class ForecostController {
  constructor(
    private readonly forecostService: ForecostService,
    private readonly dictService: DictService,
  ) {}
  @Get('/tree')
  @UseInterceptors(AuthInterceptor)
  async tree(
    @Query('itemMaster') itemMaster: string,
    @Query('org') org: string,
    @Query('code') code: string,
  ) {
    const SupplierCode = await this.forecostService.getSupplierCode('Supplier');
    // todo 临时关闭缓存
    const result = await this.forecostService.getBOMTreeService(
      null,
      org,
      code,
      itemMaster,
      SupplierCode,
      false,
    );
    if (result) {
      return Result.success(result);
    } else {
      return Result.failedWithMsg('找不到该物料编号！');
    }
  }

  @Get('/calculate')
  @UseInterceptors(AuthInterceptor)
  async calculate(
    @Query('itemMaster') itemMaster: string,
    @Query('org') org: string,
    @Query('code') code: string,
  ) {
    const SupplierCode = await this.forecostService.getSupplierCode('Supplier');
    const result = await this.forecostService.calculateService(
      null,
      org,
      code,
      itemMaster,
      SupplierCode,
      true,
      false,
    );
    let totalPrice = 0;
    let totalRunLaborHours = 0;
    for (const cal of result) {
      totalPrice += cal.price ? cal.price * cal.UsageQty : 0;
      totalRunLaborHours +=
        cal.RunLaborHours * cal.UsageQty ? cal.RunLaborHours : 0;
    }
    if (result) {
      return Result.success(result);
    } else {
      return Result.failedWithMsg('找不到该物料编号');
    }
  }

  @Post('/allBudget')
  @Header(
    'Content-Type',
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  )
  @Header('Content-Disposition', 'attachment; filename="allBudget.xlsx"')
  @UseInterceptors(AuthInterceptor)
  async allBudget(
    @Body()
    budget: {
      Org: string;
      domains: [{ Code: string; Number: number }];
    },
  ) {
    const buffer = await this.forecostService.allBudgetService(budget);
    return new StreamableFile(buffer);
  }

  @Get('/calculateAll')
  async calculateAll() {
    const SupplierCode = await this.forecostService.getSupplierCode('Supplier');
    const itemMasters = await this.forecostService.getAllBomMaster();
    const result = [];
    for (const itemMaster of itemMasters) {
      const cals = await this.forecostService.calculateService(
        null,
        '',
        '',
        itemMaster.itemMaster,
        SupplierCode,
        true,
        false,
      );
      result.push(cals);
    }
    return Result.success(result);
  }

  @Get('/err')
  @UseInterceptors(AuthInterceptor)
  async queryErr(@Query() page: { pageNum: number; pageSize: number }) {
    const result = await this.forecostService.getIFAErrs(
      page ? page : { pageNum: 1, pageSize: 10 },
    );
    return result;
  }

  @Put('')
  @UseInterceptors(AuthInterceptor)
  async upsert(@Body() bom: BomVo) {
    await this.forecostService.editBOMService(bom);
    // 更新U9工时
    const res = await RunLaborHoursCreate(
      'th',
      bom.itemMaster,
      bom.runLaborHours,
      bom.startDate,
    );
    for (const datum of res.data.Data) {
      if (datum.IsSucess == false) {
        return Result.failedWithMsg(datum.ErrorMsg);
      }
    }
    return Result.success();
  }

  @Get('')
  @UseInterceptors(AuthInterceptor)
  async getOne(@Query('itemMaster') itemMaster: string) {
    const result = await this.forecostService.getBOMByItemMaster(itemMaster);
    return Result.success(result);
  }

  @Get('/config')
  @UseInterceptors(AuthInterceptor)
  getConfig(@Query('name') name: string) {
    return this.forecostService.queryConfigService(name);
  }

  @Put('/config')
  @UseInterceptors(AuthInterceptor)
  updateConfig(@Body() body: any) {
    return this.forecostService.updateConfigService(body);
  }

  @Delete('/cache')
  @UseInterceptors(AuthInterceptor)
  rmCache(@Body() data: any) {
    return this.forecostService.rmCache(data);
  }

  @Put('/cache')
  @UseInterceptors(AuthInterceptor)
  addCache(@Query('key') key: string, @Body() data: any) {
    return this.forecostService.addCache(key, data);
  }
}
